
package com.netcracker.ui.servlet;

import com.netcracker.ui.helper.UIHelper;
import com.netcracker.util.service.ServiceFacade;
import com.netcracker.util.service.exception.DataTransmittingException;
import com.netcracker.util.service.exception.NullDataException;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.LoggerFactory;

@WebServlet(name = "ImageServlet", urlPatterns = {"/ImageServlet"})
public class ImageServlet extends HttpServlet {
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(ImageServlet.class);

    private static String getFileExtension(File file) {
        int point = file.getName().lastIndexOf('.');
        return new String(file.getName().substring(point+1));
    }
   
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Integer bookID = Integer.parseInt(request.getParameter("id"));
        ServiceFacade serviceFacade = UIHelper.getServiceFacade();
        byte[] imageContent = null;
        try {
            File imageFile = serviceFacade.getBookService().downloadBookImage(bookID);
            ByteArrayOutputStream image;
            InputStream fis = new FileInputStream(imageFile);
            image = new ByteArrayOutputStream();
            byte[] buffer = new byte[32000];
            int size = 0;
            while ((size = fis.read(buffer)) >= 0) {
                image.write(buffer, 0, size);
            }
            imageContent = image.toByteArray();
            response.setContentType("image/"+getFileExtension(imageFile));
        } catch (DataTransmittingException ex) {
            request.setAttribute("error", "Ошибка обращения к БД.");
            LOGGER.error("DB error: ", ex);
        } catch (NullDataException ex) {
            request.setAttribute("error", "Изображение не найдено.");
        }
        response.getOutputStream().write(imageContent);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }

}
